<script>
	import Vue from 'vue';

	import {
		parse,
		stringify
	} from 'lossless-json';

	import permision from "@/js_sdk/wa-permission/permission.js";
	
	import {
		mapGetters,mapState
	} from "vuex"
	
	import Tabbar from "@/pages/index/tabbar.vue"; //首页
	import Index from "@/pages/index/index.vue";
	
	import {
		getVoiceServiceList
	} from "@/api/index.js";
    
    import {
        getAPPVersion
    } from "@/api/config.js";
	
	import {getYmd} from "@/utils/data.js";
    
    import checkVersion from '@/pages/upgrade/checkVersion.js';
	
	import DB from "@/utils/sqlite.js";
	
	export default {
		globalData:{
			gdata:'gdata'
		},
		data() {
			return {
				popupVisible: false,
			};
		},
		components:{
			Tabbar,
			Index
		},
		computed: {
			...mapGetters(["userInfo","voiceServiceList","taskType"]),
			...mapState({
				voiceServiceList: state => state.task.voiceServiceList
			} )
		},
		onLaunch: function(options) {
			console.log('App onLaunch',options);
            
            let that = this;
            
            //从缓存中读取是否自动获取任务号码
            if(uni.getStorageSync("taskType") != '' && uni.getStorageSync("taskType") != null && uni.getStorageSync("taskType") != undefined){
                this.$store.dispatch("setTaskType",uni.getStorageSync("taskType"));
            }
			
			//打开SQLITE
			this.openSQL();
			
			// 重点是以下： 一定要监听后台恢复 ！一定要
			plus.globalEvent.addEventListener('newintent', (e) => {
				this.checkArguments(); // 检测启动参数
			});
			
			this.requestAndroidPermission('android.permission.READ_CALL_LOG','被永久拒绝授权, 请在设置中手动打开读取通话记录权限','未获取授权, 请打开读取通话记录权限');
			
			this.requestAndroidPermission('android.permission.RECORD_AUDIO','被永久拒绝授权, 请在设置中手动打开麦克风权限','未获取授权, 请打开麦克风权限');
			
			//判断系统是否获取所有文件权限
			const systemInfo = uni.getSystemInfoSync(); //获取系统信息，
            console.info("获取手机系统信息",systemInfo);
            this.$console.info("获取手机系统信息",systemInfo);
			if(Number(systemInfo.osVersion) >= 11){
				let environment = plus.android.importClass("android.os.Environment");
				let isExternal = environment.isExternalStorageManager();
				
				// console.log("environment",environment);
				console.log("tabbar isexternal",isExternal);
				
				if(!isExternal){
					var Intent = plus.android.importClass("android.content.Intent");
					var Settings = plus.android.importClass("android.provider.Settings");
					console.log("Settings",Settings);
					var Uri = plus.android.importClass("android.net.Uri");
					var mainActivity = plus.android.runtimeMainActivity();
					
					var intent = new Intent();
					intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);   // ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
					var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					console.log("getPackageName",mainActivity.getPackageName());
					intent.setData(uri);
					mainActivity.startActivity(intent);
				}
			}else{
				this.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE','被永久拒绝授权, 请打开写入系统文件权限','未获取授权, 请打开写入系统文件权限');
				this.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE','被永久拒绝授权, 请打开读取系统文件权限','未获取授权, 请打开系统文件权限');
			}
            
		},
		onLoad() {
			console.log('App onLoad');
            
		},
		onShow: function(options) {
			console.log('App onShow',options,this.$globalData.taskTimer);
            
            //  进入页面的时候执行一次
            uni.getSystemInfo({
            	success: function (res) {
                    console.log("onshow getsysteminfo",res);
            		const windowWidth = res.windowWidth;   // 窗口宽度
            		const windowHeight = res.windowHeight; // 窗口高度
            		console.log("windowWidth",windowWidth);
            		console.log("windowHeight",windowHeight);
            	}
            });
			
			//获取平台信息
			// this.$callModule.getSettingsKeyValue(res=>{
			//     console.log("getSettingsKeyValue res",res);
			    
			//     //保存到日志
			//     this.$console.info("平台信息--参数 ", JSON.stringify(res));
			// });
            
            //检测升级
            let baseApiUrl = uni.getStorageSync("baseApiUrl");
            if(baseApiUrl != "" && baseApiUrl != null && baseApiUrl != undefined){
                console.log("onshow  检测是否需要升级");
                this.$console.info("onshow  检测是否需要升级");
                getAPPVersion().then(res=>{
                    console.log("onshow  检测是否需要升级,获取结果：",res);
                    this.$console.info("onshow  检测是否需要升级,获取结果：",res);
                    if (res.data.code == 200) {
                        let appData = res.data.data;
                        if (appData != null && appData != '') {
                            let name= "新版本V" + appData.app_version;//新版本名称
                            let code= appData.app_version_code; //新版本号（数字）
                            let url= appData.download_url;//app下载链接，（演示请换成真正在下载链接）
                            let forceUpdate = appData.is_force == 1 ? true : false;//是否强制更新
                            
                            let content = appData.app_content == null ? '' : `${appData.app_content}`;//更新内容
                            
                            console.log("onshow  检测是否需要升级,升级内容：",name,code,content,url,forceUpdate);
                            this.$console.info("onshow  检测是否需要升级,升级内容：",name,code,content,url,forceUpdate);
                            
                            checkVersion({
                                name,//最新版本名称
                                code,//最新版本号
                                content,//更新内容
                                url,//下载链接
                                forceUpdate//是否强制升级			  
                            });
                        }
                    }
                });
            }
            
            //console.log("this.$callModule",callModule);
            
            //获取当前手机号码
            // if(this.$callModule != undefined){
            //     this.$callModule.getPhoneNumber(res => {
            //         this.$globalData.userPhoneNumber = res.data.numbers;
                    
            //         console.log("userphonenumber res",res);
            //     })
            // }
            
            
			//手机屏幕常亮
			// uni.setKeepScreenOn({
			//     keepScreenOn: true
			// });
			
			if(this.taskType == 0 && this.$globalData.taskTimer == null){
			    this.$globalData.taskTimer = setInterval(()=>{
                    this.$console.info("APP启动 onShow 启动定时任务",this.taskType,this.$globalData.taskTimer);
			        uni.$emit("handleGetCall","");
			    },2000);
			}
		},
		onHide: function() {
			console.log('App onHide',this.$globalData.taskTimer);
			
			clearInterval(this.$globalData.taskTimer);
			this.$globalData.taskTimer = null;
            
            // clearInterval(this.$globalData.threadTimer);
            // this.$globalData.threadTimer = null;
		},

		methods: {                
			checkArguments() {
				const that = this
				var args = plus.runtime.arguments;
				if (args) {
					let args1 = parse(args);
					console.log(" checkarguments args:",args1);
				}
			},
			
			//打开SQLITE
			openSQL(){
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				console.log('APP 数据库状态', open ? '开启' : '关闭');
				this.$console.log('APP 数据库状态', open ? '开启' : '关闭');
				if (!open) {
					//没打开，重新打开SQLITE
				    DB.openSqlite().then((res) => {
				        console.log('APP 数据库已打开');
                        this.$console.info('APP 数据库已打开');
						
						//检测SQLITE状态，并做数据处理
						this.createTable();
				    }).catch((error) => {
				        console.log('APP 数据库开启失败');
						this.$console.info('APP 数据库开启失败');
				    })
				}else{
					//检测SQLITE状态，并做数据处理
					this.createTable();
				}
			},
			
			//SQLITE数据处理
			createTable() {
			    // let open = DB.isOpen();
				let _this = this;
				
				//测试删除数据表
				// DB.dropTable("call_cdr_list");
				
				//判断表是否存在
				DB.existsTable("call_cdr_list").then(res=>{
					console.log("call_cdr_list_table",res);
					
					if(!res){
						//通话记录表 type:类型，status:状态，0未上传录音，1已上传录音
						let sql = '"id" INTEGER PRIMARY KEY AUTOINCREMENT,"seat" text,"num" text,"stime" text,"etime" text,"atime" text,"type" text,"cid" text,"pid" text,"tid" text,"audio_path" text,"cdr_id" text,"status" text,"cdr_status" text,"sec" text,"ctime" text,"remark" text';
						// 创建表 DB.createTable(表名, 表的列)
						DB.createTable('call_cdr_list', sql).then((res) => {
							console.log('APP 创建call_cdr_list表成功');
							_this.$console.info('APP 创建call_cdr_list表成功');
							
							// _this.closeSQL();
						}).catch((error) => {
							console.log('APP 创建表失败');
							_this.$console.info('APP 创建表失败');
						});
					}else{
						//删除今天前的数据
						let delete_time = getYmd() + " 00:00:00";
						DB.deleteTableDataWhere("call_cdr_list","ctime < '"+delete_time+"'").then(res_del=>{
                            console.log("APP 删除昨天的数据",res_del);
                            _this.$console.info('APP 删除昨天的数据',res_del);
                        }).catch(err_del=>{
                            console.log('APP 查询表是否存在 error',err_del);
                            _this.$console.info('APP 查询表是否存在 error',err_del);
                        });
					}
				}).catch(err=>{
					console.log('APP 查询表是否存在 error',err);
					_this.$console.info('APP 查询表是否存在 error',err);
				});
			},
			
			// 关闭数据库
			closeSQL() {
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				if (open) {
					DB.closeSqlite().then((res) => {
						console.log('数据库已关闭')
					}).catch((error) => {
						console.log('数据库关闭失败')
					});
				}
			},
			
			
			// vue的method里编写如下代码
			async requestAndroidPermission(permisionID,errmsg1,errmsg2) {
			    await permision.requestAndroidPermission(permisionID).then(res => {
					console.log("res",res);
					this.$console.log("授权信息:",permisionID,errmsg1,errmsg2);
					this.$console.log("授权信息 结果:",res);
					if(res==1){
						//resolve();
					}else if(res == 0){
						uni.showModal({
							title: '提示',
							// content: '被永久拒绝授权, 请打开拨打电话权限',
							content:errmsg1,
							success() {
								permision.gotoAppPermissionSetting();
							}
						});
						//reject();
					}else if(res == -1){
						uni.showModal({
							title: '提示',
							// content: '未获取授权, 请打开拨打电话权限',
							content: errmsg2,
							success() {
								permision.gotoAppPermissionSetting();
							}
						});
						//reject();
					}
				})
			},
			
			//退出时清空缓存
			clearAppCache(){
				let os = plus.os.name;
				if (os == 'Android') {
					let main = plus.android.runtimeMainActivity();
					let sdRoot = main.getCacheDir();
					let files = plus.android.invoke(sdRoot, "listFiles");
                    if(files != undefined && files != null){
                        let len = files.length;
                        for (let i = 0; i < len; i++) {
                            let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
                            // console.log("filePath",filePath);
                            plus.io.resolveLocalFileSystemURL(filePath, function(entry) {						
                                if (entry.isDirectory) {
                                    entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
                                        // uni.showToast({
                                        // 	title: '缓存清理完成',
                                        // 	duration: 2000
                                        // });
                                        //that.formatSize(); // 重新计算缓存  
                                    }, function(e) {
                                        console.log(e.message)
                                    });
                                } else {
                                    entry.remove();
                                }
                            }, function(e) {
                                console.log('文件路径读取失败')
                            });
                        }
                    }
				}
			}
		},
		
		beforeDestroy: function() {
			console.log("app beforeDestroy");
		},
		
	}
</script>

<style lang="scss">
	@import "colorui/main.css";
	@import "colorui/icon.css";
	@import "uview-ui/index.scss";
	@import "styles/main.scss";
	
	@import url("static/font/iconfont.css");
    
</style>